// pages/home//unit/unit.js
import {
  http
} from '../../../utils/apiutils'
import { formatTime, getAge } from '../../../utils/util'
import { url } from '../../../utils/config'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    showCalendar: false,
    dataList: [],
    paramsList: {
      name: '',
      createTime: '',
      jobId: '',
      pageNo: 1,
      pageSize: 10
    },
    hasMore: true,
    loading: false,
    totalNum: 0,
    totalMoney: 0,
    date: formatTime(new Date().getTime()),
    minDate: new Date(2018, 0, 1).getTime(),
    maxDate: new Date().getTime(),
    unitType:''

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      ['paramsList.jobId']: options.id,
      unitType:options.type
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.setData({
      dataList:[],
      totalNum: 0,
      totalMoney: 0,
      ['paramsList.pageNo']: 1,
      ['paramsList.createTime']: this.data.date,
    })
    this.getUnitList(this.data.paramsList)

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if (this.data.loading) {
      return
    }
    if (!this.data.hasMore) {
      this.setData({
        ['paramsList.pageNo']: 1
      })
      return
    }
    this.setData({
      ['paramsList.pageNo']: this.data.paramsList.pageNo + 1
    })
    this.getUnitList(this.data.paramsList)

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  // 获取数据列表
  getUnitList(params) {
    var that = this
    that.data.loading = true
    wx.showLoading()
    http.getUnitList(params, res => {
      wx.hideLoading()
      if (res.status == 200) {
        if (res.obj.pageList.records && res.obj.pageList.records.length > 0) {
          res.obj.pageList.records.map(item => {
            item.age = item.idNumber ? getAge(item.idNumber) : ''
          })
          that.setData({
            dataList: [...that.data.dataList, ...res.obj.pageList.records],
            loading: false,
            hasMore: res.obj.pageList.records.length > 0 ? true : false,
            totalNum: res.obj.todayNum,
            totalMoney: res.obj.todayAmount
          })
        } else {
          that.setData({
            ['paramsList.pageNo']: 1,
            loading: false,
            hasMore: false
          })
          wx.showToast({
            title: '加载完成',
            icon: 'none'
          })
        }
      } else {
        wx.showToast({
          title: res.msg,
          icon: 'none'
        })
      }
    }, err => {
      wx.hideLoading()
      wx.showToast({
        title: '获取数据失败',
        icon: 'none'
      })
    })
  },
  onValueChange(e) {
    this.setData({
      ['paramsList.name']: e.detail
    })
  },
  onSearch() {
    this.setData({
      dataList: [],
      hasMore: true,
      loading: false,
      ['paramsList.pageNo']: 1
    })
    this.getUnitList(this.data.paramsList)
  },
  onClear() {
    this.setData({
      dataList: [],
      hasMore: true,
      loading: false,
      ['paramsList.pageNo']: 1,
      ['paramsList.name']: ''
    })
    this.getUnitList(this.data.paramsList)
  },
  toScanUnit() {
    wx.navigateTo({
      url: '/pages/home/scanUnit/scanUnit?id=' + this.data.paramsList.jobId+'&&type='+this.data.unitType,
    })
  },
  onDisplay() {
    this.setData({
      showCalendar: true
    })
  },
  onCalendarClose() {
    this.setData({
      showCalendar: false,
    })
  },
  formatDate(date) {
    date = new Date(date);
    return formatTime(date);
  },
  onCalendarConfirm(event) {
    // let dqtime=new Date().getTime()
    // let aftime=event.detail.getTime()
    // if(aftime>dqtime){
    //   wx.showToast({
    //     title: '选择日期不能大于今天',
    //     icon:'none'
    //   })
    //   return
    // }
    this.setData({
      showCalendar: false,
      dataList: [],
      hasMore: true,
      loading: false,
      totalNum:0,
      totalMoney:0,
      ['paramsList.pageNo']: 1,
      ['paramsList.createTime']: this.formatDate(event.detail),
      date:this.formatDate(event.detail),
    })
    this.getUnitList(this.data.paramsList)
  },
  toUnitDetail(e) {
    let jId=e.currentTarget.dataset.info.jobId
    let uId=e.currentTarget.dataset.info.userId
    let name=e.currentTarget.dataset.info.name
    let cTime=this.data.paramsList.createTime
    wx.navigateTo({
      url: '/pages/home/unitDetail/unitDetail?jId='+jId+'&&uId='+uId+'&&cTime='+cTime+'&&name='+name,
    })
  },
  // 导入
  uploadData(){
    if(this.data.dataList.length>0){
      wx.showToast({
        title: '已存在数据记录，暂不支持导入',
        icon:'none'
      })
      return
    }
    const that=this
    wx.chooseMessageFile({
      count: 1,
      type:'file',
      success(res){
        const path=res.tempFiles[0].path
        let filename=res.tempFiles[0].name
        let size=res.tempFiles[0].size
        if(filename.indexOf('.xlsx')==-1){//限制文件类型
          wx.showModal({
            title: '提示',
            content:'文件类型必须为excel！(.xls)',
            confirmColor: '#FF7D19',
            confirmText:'确定',
            success:function(res){}
          })
        }else{
          wx.showModal({
            title: '提示',
            content:'确定上传'+filename+'?',
            confirmColor: '#FF7D19',
            confirmText:'上传',
            success:function(res){
              if(res.confirm){
                wx.showLoading({
                  title:'上传中'
                })
                wx.uploadFile({
                  url: url+'/api/upload/file',
                  header: {
										"content-type": "application/vnd.ms-excel",
										"Authorization": "Bearer " + getApp().globalData.token
									},
                  filePath: path,
                  name: 'file', //后台获取的凭据
                  success(res){
                    wx.hideLoading()
                    let resp=JSON.parse(res.data)
                    let pathArr=resp.data.split('/')
                    if(resp.code==0){
                      wx.showToast({
                        title: resp.message,
                        icon:'none'
                      })
                      // 提交
                      let params={
                        jobId:that.data.paramsList.jobId-0,
                        dateStr:that.data.paramsList.createTime,
                        filePath:pathArr[pathArr.length-1]
                      }
                      let currentDate=formatTime(new Date().getTime()).split(' ')[0]
                      if(params.dateStr==currentDate){
                        wx.showToast({
                          title: '请导入小于今天的过往日期',
                          icon:'none'
                        })
                        return
                      }
                      that.exportUnitData(params)

                    }else{
                      wx.showToast({
                        title: '上传失败',
                        icon:'none'
                      })
                    }
                  },
                  file(err){
                    wx.hideLoading()
                    wx.showModal({
											title: '提示',
											content: "文件上传失败" + err.errMsg,
											showCancel: false, //是否显示取消按钮
											success: function (result) {
											}
										})
                  }
                })
              }
            }
          })
        }

      }
    })
  },
  exportUnitData(params){
    var that=this
    http.exportUnitData(params,res=>{
      wx.showToast({
        title: res.msg,
        icon:'none'
      })
      console.log('8888',res)
      if(res.status==200){
        that.setData({
          dataList: [],
          hasMore: true,
          loading: false,
          ['paramsList.pageNo']: 1,
          ['paramsList.name']: ''
        })
        that.getUnitList(that.data.paramsList)
      }
    },err=>{
     wx.showToast({
       title: '操作失败',
       icon:'none'
     })
    })
  }
})